package utils;

import java.awt.Image;
import java.io.File;
import java.util.HashMap;

import javax.swing.ImageIcon;

import enums.Direction;
import enums.PlayerColor;
import enums.Revealed;
import enums.Weapon;
import utils.SwingWorker;
import utils.Piece;


/**
 * A singleton class that prepares and then give access to all the different images of the pieces in the game.
 */
public class GameImages {
	
	private static GameImages instance = null;
	
	private boolean finishedLoading = false;
	private HashMap<String, ImageIcon> imagesMap = new HashMap<String, ImageIcon>();
	
	
	private GameImages() {
		
        final SwingWorker worker = new SwingWorker() {
         
        	public Object construct() {
        		for (PlayerColor color : PlayerColor.values())
        			for (Direction direction : Direction.values())
        				for (Weapon weapon : Weapon.values())
        					for (Revealed revealed : Revealed.values()) {
	        					Piece piece = new Piece(color, direction, weapon ,revealed);
	        					addImage(piece.getMap(), piece.filePosition());
	        				}
                GameImages.finishedLoaded();
                return null;
            }
        };
        worker.start();
	};

    public static ImageIcon getImageIcon (String key) {
    	while (!isFinishedLoading ()) {
    	}
    	return getInstance().imagesMap.get(key);
    }
    
	public static synchronized GameImages getInstance () {
		if (instance == null) {
			instance = new GameImages ();
		}
		return instance;
	}

	public static Image getImage (String key) {
        ImageIcon imageIcon = getImageIcon(key);
        if (imageIcon != null) {
            return imageIcon.getImage();
        }
		return null;
	}
	
	private static void finishedLoaded () {
		getInstance().finishedLoading = true;
	}
	
	private static boolean isFinishedLoading () {
		return getInstance().finishedLoading;
	}
	
	private static void addImage (String key, String path) {
		try{
			File file = new File(path);
			if (file.exists()) {
				ImageIcon imageIcon = new ImageIcon (path);
				getInstance().imagesMap.put (key, imageIcon);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
